﻿package com.gamemeal.view{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.IBitmapDrawable;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.filters.BitmapFilter;
	import flash.geom.Point;
	import flash.media.Camera;
	import flash.media.Video;
	import flash.text.AntiAliasType;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.text.TextFormat;
	/**
	 * @author Colin
	 */
	public class CameraView extends Sprite {
		private var txf : TextField;
		private var ctx : BitmapData;
		private var origin : Point = new Point(0,0);
		private var video : IBitmapDrawable;
		private var cameraIndex : int;
		private var _filters:Array=[];
		private var camWidth:int = 160;
		private var camHeight:int = 120;

		private var englishTextFormat:TextFormat=new TextFormat("HelveticaNeueLT Std Blk Cn",9,0xE0E0E0);
		private var chineseTextFormat:TextFormat=new TextFormat("華康黑體 Std W9",10,0xE0E0E0);

		public function CameraView(imgSource:IBitmapDrawable=null,cameraIndex:int=0,w:int=160,h:int=120){
			this.ctx = new BitmapData(w,h,false,0xf0f0f0);
			this.cameraIndex = cameraIndex;
			this.camWidth = w;
			this.camHeight = h;

			video = (video is IBitmapDrawable)?makeVideo():imgSource;

			txf = makeTextField();
			this.addChild(new Bitmap(ctx));
			this.addChild(txf);

			title="";
			this.addEventListener(Event.ENTER_FRAME,loop,false,0,true);
		}

		public function addFilter(filter : *):void{
			_filters.push(filter);
		}

		private function loop(e:Event=null):void{
			ctx.draw(video);
			for(var i:int=0;i<_filters.length;i++){
				if(_filters[i] is BitmapFilter){
					ctx.applyFilter(ctx,ctx.rect, origin, _filters[i]);
				}else{
					_filters[i].apply(ctx);
				}
			}
		}

		private function makeTextField():TextField{
			var t:TextField = new TextField();
			t.autoSize = TextFieldAutoSize.LEFT;
			t.embedFonts = true;
			t.antiAliasType = AntiAliasType.ADVANCED;
			t.selectable = false;
			t.x = 2;
			t.y = camHeight-16;
			return t;
		}

		private function makeVideo():Video{
			var v:Video = new Video(camWidth,camHeight);
			var cam:Camera = Camera.getCamera(String(cameraIndex));
			cam.setMode(camWidth,camHeight,30);
			cam.setQuality(0, 100);
			v.attachCamera(cam);
			return v;
		}

		public function set title(str:String):void{
			if(str==""){
				txf.defaultTextFormat = chineseTextFormat;
				txf.text = "空";
			}else{
				txf.defaultTextFormat = englishTextFormat;
				txf.text = str;
			}
		}
		
		public function get context() : BitmapData{
			return ctx;
		}
	}
}